(function (exports) {

    var $ = null;
    var node = null;
    var effectEmojiQueue = {};
    var effectEmojiCfg = {
        1: {'name': 'zan', 'startFrames': 9, 'endFrames': 10, 'offsetX': 0, 'offsetY': 0},
        2: {'name': 'bomb', 'startFrames': 0, 'endFrames': 10, 'offsetX': 3, 'offsetY': 11},
        3: {'name': 'egg', 'startFrames': 9, 'endFrames': 10, 'offsetX': 0, 'offsetY': 22},
        4: {'name': 'shoe', 'startFrames': 5, 'endFrames': 10, 'offsetX': -1, 'offsetY': -1},
        5: {'name': 'flower', 'startFrames': 11, 'endFrames': 13, 'offsetX': 0, 'offsetY': 0}
    };
    var onSendEffectEmoji = function (emojiIdx, times, targetUid) {
        if (!cc.sys.isObjectValid(node)) return;
        var _obj = [];
        _obj.push(targetUid);
        if(isNiuniu()){
            var msg = JSON.stringify({
                roomid: gameData.roomId, type: 'effectemoji',
                content: JSON.stringify({
                    from_uid: gameData.uid,
                    emoji_idx: emojiIdx,
                    emoji_times: times,
                    target_uid: _obj,
                }),
                from: gameData.uid
            });
            network.wsData("Say/" + msg);
        }else {
            network.send(4990, {room_id: gameData.roomId, emoji_idx: emojiIdx, emoji_times: times, target_uid: _obj});
        }
    };
    var addEffectEmojiQueue = function (caster, patientList, emojiId, times) {
        if (!cc.sys.isObjectValid(node)) return;
        var _casterRow = node.getRowByUid(caster);
        var _patientRowList = [];
        for (var _j = 0; _j < patientList.length; _j++) {
            _patientRowList.push(node.getRowByUid(patientList[_j]));
        }
        if (_.isUndefined(effectEmojiQueue[_casterRow])) {
            effectEmojiQueue[_casterRow] = [];
        }
        var _needBigenQueue = isEffectEmojiEmpty();
        var _obj = {};
        _obj.patientList = _patientRowList;
        _obj.emojiId = emojiId;
        for (var _i = 0; _i < times; _i++) {
            effectEmojiQueue[_casterRow].push(_obj);
        }
        if (_needBigenQueue) {
            startEffectEmojiQueue();
        }
    };
    var isEffectEmojiEmpty = function () {
        if (!cc.sys.isObjectValid(node)) return true;
        for (var _key in effectEmojiQueue) {
            if (effectEmojiQueue.hasOwnProperty(_key)) {
                if (effectEmojiQueue[_key].length > 0) {
                    return false;
                }
            }
        }
        return true;
    };
    var startEffectEmojiQueue = function () {
        if (!cc.sys.isObjectValid(node)) return;
        for (var _key in effectEmojiQueue) {
            if (effectEmojiQueue.hasOwnProperty(_key)) {
                var _obj = effectEmojiQueue[_key];
                if (_obj.length > 0) {
                    for (var _i = 0; _i < _obj[0].patientList.length; _i++) {
                        playEffectEmoji(_key, _obj[0].patientList[_i], _obj[0].emojiId);
                    }
                    effectEmojiQueue[_key].splice(0, 1);
                }
            }
        }
        if (!isEffectEmojiEmpty()) {
            node.runAction(cc.sequence(
                cc.delayTime(0.3),
                cc.callFunc(function () {
                    startEffectEmojiQueue();
                })
            ))
        }
    };
    var playEffectEmoji= function (caster, patient, emojiId) {
        if (!cc.sys.isObjectValid(node)) return;
        var _emojiCfg = effectEmojiCfg[emojiId];
        if (_.isUndefined(_emojiCfg)) {
            return;
        }
        var sp = new cc.Sprite();
        node.getRootNode().addChild(sp, 30);
        var _frame = cc.spriteFrameCache.getSpriteFrame(_emojiCfg.name + 'temp.png');
        if (!_frame) {
            cc.spriteFrameCache.addSpriteFrames(res['effect_emoji_' + _emojiCfg.name]);
            _frame = cc.spriteFrameCache.getSpriteFrame(_emojiCfg.name + 'temp.png');
        }
        effectEmojiBegin(_emojiCfg, sp, _frame, caster, patient);
    };
    var effectEmojiBegin= function (emojiCfg, sp, frame, caster, patient) {
        if (!cc.sys.isObjectValid(node)) return;
        var midUserPos = 2;
        if(isNiuniu()) midUserPos = 0;
        var _beginPos = $('effectemoji' + caster).getPosition();
        var _endPos = patient != midUserPos ? $('effectemoji' + patient).getPosition() : cc.p(cc.winSize.width / 2, cc.winSize.height / 2);
        sp.setPosition(_beginPos);
        if (emojiCfg.name != 'bomb') {
            playFrameAnim2(res['effect_emoji_' + emojiCfg.name], emojiCfg.name + 'start', 1, emojiCfg.startFrames, 0.05, false, sp, function () {
                effectEmojiflying(emojiCfg, sp, frame, caster, patient);
            })
        }
        if (emojiCfg.name == 'bomb') {
            var _shvlitime, _shvlirotate;
            if (_beginPos.x > _endPos.x) {
                _shvlitime = 0.2;
                _shvlirotate = 45;
            } else if (_beginPos.x < _endPos.x) {
                _shvlitime = 0.2;
                _shvlirotate = -45;
            } else {
                _shvlitime = 0.1;
                _shvlirotate = 0;
            }
            sp.setSpriteFrame(frame);
            sp.runAction(cc.sequence(
                cc.moveBy(0, 0, 40),
                cc.moveBy(0.3, 0, -40).easing(cc.easeIn(1.5)),
                cc.rotateBy(0.1, -10).easing(cc.easeOut(1.5)),
                cc.rotateBy(0.1, 20).easing(cc.easeOut(1.5)),
                cc.rotateBy(0.1, -10).easing(cc.easeOut(1.5)),
                cc.delayTime(0.1),
                cc.rotateBy(_shvlitime, _shvlirotate).easing(cc.easeOut(1.5)),
                cc.delayTime(_shvlitime * 1),
                cc.callFunc(function () {
                    effectEmojiflying(emojiCfg, sp, frame, caster, patient);
                })
            ))
        }
    };
    var effectEmojiflying= function (emojiCfg, sp, frame, caster, patient) {
        if (!cc.sys.isObjectValid(node)) return;
        var midUserPos = 2;
        if(isNiuniu())  midUserPos = 0;
        var _beginPos = $('effectemoji' + caster).getPosition();
        var _endPos = patient != midUserPos ? $('effectemoji' + patient).getPosition() : cc.p(cc.winSize.width / 2, cc.winSize.height / 2);
        sp.stopAllActions();
        sp.setSpriteFrame(frame);
        var _flyRotate;
        if (emojiCfg.name == 'bomb') {
            if (_beginPos.x > _endPos.x) {
                _flyRotate = -105;
            } else if (_beginPos.x < _endPos.x) {
                _flyRotate = 105;
            } else {
                _flyRotate = 0;
            }
            sp.runAction(cc.rotateBy(0.5, _flyRotate));
        } else if (emojiCfg.name == 'egg' || emojiCfg.name == 'shoe') {
            if (_beginPos.x <= _endPos.x) {
                _flyRotate = 360;
            } else {
                _flyRotate = -360;
            }
            sp.runAction(cc.rotateBy(0.5, _flyRotate * 5));
        }
        sp.runAction(cc.sequence(
            patient != midUserPos ? cc.moveTo(0.5, _endPos) : cc.spawn(cc.moveTo(0.5, _endPos), cc.scaleTo(0.5, 4)),
            cc.callFunc(function () {
                effectEmojiend(emojiCfg, sp, frame, caster, patient);
            })
        ));
    };
    var effectEmojiend= function (emojiCfg, sp, frame, caster, patient) {
        if (!cc.sys.isObjectValid(node)) return;
        var midUserPos = 2;
        if(isNiuniu())  midUserPos = 0;
        var _beginPos = $('effectemoji' + caster).getPosition();
        var _endPos = patient != midUserPos ? $('effectemoji' + patient).getPosition() : cc.p(cc.winSize.width / 2, cc.winSize.height / 2);
        var _offsetX = patient == midUserPos ? emojiCfg.offsetX * 4 : emojiCfg.offsetX;
        var _offsetY = patient == midUserPos ? emojiCfg.offsetY * 4 : emojiCfg.offsetY;
        if (emojiCfg.name != 'bomb') {
            sp.setRotation(0);
            sp.setPosition(cc.p(sp.getPositionX() + _offsetX, sp.getPositionY() + _offsetY));
            playFrameAnim2(res['effect_emoji_' + emojiCfg.name], emojiCfg.name + 'end', 1, emojiCfg.endFrames, 0.05, false, sp, function () {
                sp.runAction(cc.sequence(
                    cc.fadeOut(0.3),
                    cc.callFunc(function () {
                        sp.removeFromParent(false);
                    })
                ))
            })
        }
        if (emojiCfg.name == 'bomb') {
            sp.setSpriteFrame(frame);
            var _flag = 1;
            if (_beginPos.x > _endPos.x) {
                _flag = 1;
            } else if (_beginPos.x < _endPos.x) {
                _flag = -1;
            } else {
                _flag = 0;
            }
            sp.runAction(cc.sequence(
                cc.rotateBy(0.1 * Math.abs(_flag), 110 * _flag).easing(cc.easeOut(1.5)),
                cc.rotateBy(0.1 * Math.abs(_flag), -80 * _flag).easing(cc.easeOut(1.5)),
                cc.rotateBy(0.1 * Math.abs(_flag), 50 * _flag).easing(cc.easeOut(1.5)),
                cc.rotateBy(0.1 * Math.abs(_flag), -20 * _flag).easing(cc.easeOut(1.5)),
                cc.callFunc(function () {
                    sp.setRotation(0);
                    sp.setPosition(cc.p(sp.getPositionX() + _offsetX, sp.getPositionY() + _offsetY));
                    playFrameAnim2(res['effect_emoji_' + emojiCfg.name], emojiCfg.name + 'end', 1, emojiCfg.endFrames, 0.05, false, sp, function () {
                        sp.runAction(cc.sequence(
                            cc.fadeOut(0.3),
                            cc.callFunc(function () {
                                sp.removeFromParent(false);
                            })
                        ))
                    })
                })
            ))
        }
    };

    exports.EFFECT_EMOJI = {
        init: function (_node, _$) {
            node = _node;
            $ = _$;
            effectEmojiQueue = {};
            network.addListener(4990, function (data) {
                addEffectEmojiQueue(data.from_uid, data.target_id, data.emoji_idx, data.emoji_times);
            });
        },
        destroy: function () {
            node = null;
            $ = null;
        }
    };

    exports.PlayerInfoLayer = {
        init: function (playerInfo, node, canDropAni) {
            var that = node;
            var scene = that.getChildByName('playerinfo');

            if(canDropAni == null || canDropAni == undefined){
                canDropAni = true;
            }

            if(scene) {
                scene.removeFromParent(true);
            }

            if (playerInfo.uid == gameData.uid) {
                scene = ccs.load(res.PlayerInfo_json).node;
            }else {
                scene = ccs.load(res.PlayerInfoOther_json).node;
            }
            scene.setName('playerinfo');
            that.addChild(scene, 200);


            var targetUid = playerInfo.uid;

            var head = $('root.panel.head', scene);
            var lbNickname = $('root.panel.lb_nickname', scene);
            var lbId = $('root.panel.lb_id', scene);
            var lbIp = $('root.panel.lb_ip', scene);
            var male = $('root.panel.male', scene);
            var female = $('root.panel.female', scene);
            var lbDt = $('root.panel.lb_dt', scene);


            lbNickname.setString(ellipsisStr(playerInfo['nickname'], 7));
            loadImageToSprite(playerInfo['headimgurl'], head);
            lbId.setString(playerInfo['uid']);
            lbIp.setString(playerInfo['ip']);

            if (lbDt) {

                if (playerInfo.uid == gameData.uid)
                    lbDt.setVisible(false);
                else
                    lbDt.setVisible(true);
                if (!gameData.location || playerInfo['loc'] == '' || !playerInfo['loc'] || playerInfo['loc'] == 'false' || gameData.location == 'false') {
                    lbDt.setVisible(false);
                } else {
                    var templocation1 = playerInfo['loc'].split(',');
                    var otherpeoplelocationlat = templocation1[1];
                    var otherpeoplelocationlng = templocation1[0];
                    var templocation2 = gameData.location.split(',');
                    var mylocationlat = templocation2[1];
                    var mylocationlng = templocation2[0];
                    // console.log(otherpeoplelocationlat+':'+otherpeoplelocationlng+':'+mylocationlat+':'+mylocationlng);
                    if (playerInfo.uid == gameData.uid)
                        lbDt.setVisible(false);
                    else
                        lbDt.setVisible(true);
                    var distance = LocationUtils.getFlatternDistance(mylocationlat, mylocationlng, otherpeoplelocationlat, otherpeoplelocationlng);
                    if (distance >= 1000) {
                        lbDt.setString('距我 ' + Math.round(distance / 1000) + '公里');
                    }
                    else {
                        lbDt.setString('距我 ' + distance + '米');
                    }
                }

            }

            // if (lbDt) {
            //     // if (idx == 2) {
            //     //     if (gameData.location == 'false')
            //     //         lbAD.setString('自己' + decodeURIComponent(gameData.locationInfo));
            //     //     else if (!gameData.location || gameData.location == '') {
            //     //         lbAD.setString('您可能没有开启定位权限');
            //     //     } else
            //     //         lbAD.setString(decodeURIComponent(gameData.locationInfo));
            //     // } else {
            //     //     if (playerInfo['loc'] == 'false')
            //     //         lbAD.setString('对方' + decodeURIComponent(playerInfo['locCN']));
            //     //     else
            //     //         lbAD.setString(decodeURIComponent(playerInfo['locCN']));
            //     // }
            //     if (!gameData.location || playerInfo['loc'] == '' || !playerInfo['loc'] || playerInfo['loc'] == 'false' || gameData.location == 'false') {
            //         // lbDt.setVisible(false);
            //     } else {
            //         var templocation1 = playerInfo['loc'].split(',');
            //         var otherpeoplelocationlat = templocation1[1];
            //         var otherpeoplelocationlng = templocation1[0];
            //         var templocation2 = gameData.location.split(',');
            //         var mylocationlat = templocation2[1];
            //         var mylocationlng = templocation2[0];
            //         // console.log(otherpeoplelocationlat+':'+otherpeoplelocationlng+':'+mylocationlat+':'+mylocationlng);
            //         if (playerInfo.uid == gameData.uid);
            //             // lbDt.setVisible(false);
            //         else
            //             // lbDt.setVisible(true);
            //         var distance = LocationUtils.getFlatternDistance(mylocationlat, mylocationlng, otherpeoplelocationlat, otherpeoplelocationlng);
            //         if (distance >= 1000) {
            //             // lbDt.setString('距我 ' + Math.round(distance / 1000) + '公里');
            //         }
            //         else {
            //             // lbDt.setString('距我 ' + distance + '米');
            //         }
            //     }
            // }
            // lbLocation.setString('位置: ' + ellipsisStr(gameData.location || "未知位置", 30));

            male.setVisible(playerInfo.sex == '1');
            female.setVisible(playerInfo.sex == '2');

            TouchUtils.setOnclickListener($('root.fake_root', scene), function () {
                scene.setVisible(false);
            });
            TouchUtils.setOnclickListener($('root.panel', scene), function () {
            }, {effect: TouchUtils.effects.NONE});

            if (playerInfo.uid != gameData.uid) {
                for (var i = 1; i <= 5; i++) {
                    (function (k) {
                        $('root.panel.other.emoji' + k, scene).setVisible(canDropAni);
                        TouchUtils.setOnclickListener($('root.panel.other.emoji' + k, scene), function () {
                            onSendEffectEmoji(k, 1, targetUid);
                            for (var j = 1; j <= 5; j++) {
                                (function (j) {
                                    var timer = scene.getChildByName('timer');
                                    var zhezhao = duplicateSprite($('zhezhao', scene));
                                    var processTimer = new cc.ProgressTimer(timer)
                                    processTimer.setType(cc.ProgressTimer.TYPE_RADIAL)
                                    if (cc.sys.isNative)
                                        processTimer.setReverseDirection(true)
                                    else
                                        processTimer.setReverseProgress(true)
                                    processTimer.setPercentage(100);
                                    processTimer.setPosition($('root.panel.other.emoji' + j, scene).getPosition());
                                    zhezhao.setPosition($('root.panel.other.emoji' + j, scene).getPosition());
                                    $('root.panel.other', scene).addChild(processTimer);
                                    $('root.panel.other', scene).addChild(zhezhao);
                                    processTimer.runAction(cc.sequence(cc.progressTo(3, 0)));
                                    processTimer.schedule(function () {
                                        processTimer.removeFromParent(true);
                                        zhezhao.removeFromParent(true);
                                    }, 3, 3 - 1, 0)
                                })(j)

                            }

                            scene.setVisible(false);
                        });
                    })(i);
                }
            }
        }
    }
    exports.PlayerInfoLayer.addEffectEmojiQueue = addEffectEmojiQueue;
})(this);